package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignServise;
import com.atguigu.gulimall.auth.vo.SocialUserVo;
import com.atguigu.common.vo.MemberRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignServise memberFeignServise;

    @GetMapping("/oauth2.0/weibo/succes")
    public String weibo(@RequestParam("code") String code, RedirectAttributes attributes, HttpSession session, HttpServletResponse servletResponse) throws Exception {

        Map<String, String> header = new HashMap();
        Map<String, String> query = new HashMap();
        Map<String, String> map = new HashMap();
        map.put("client_id", "注册的或者ID");
        map.put("client_secret", "注册开发端口的时候分配的秘钥");
        map.put("grant_type", "授权码");
        map.put("redirect_url", "登录成功要回调的URL");
        map.put("code", code);
        HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/oauth2.0/access_token", "GET", map, query);

        //处理响应
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUserVo userVo = JSON.parseObject(json, SocialUserVo.class);
            R r = memberFeignServise.oauthLogin(userVo);
            if (r.getCode() == 0) {
                MemberRegisterVo data = r.getDate("data", new TypeReference<MemberRegisterVo>() {
                });
                attributes.addFlashAttribute("data", data);
                /**
                 * 登录成功,用户第一次使用session,命令浏览器保存session,SESSIONID这个cookie
                 * 以后浏览器访问哪个网站就会带上这个网站的cookie
                 * 解决子域名之间的访问:
                 * 服务器创建session的时候指定某个域名为父域名,即使是子域系统创建的session,也能让父域名直接使用
                 * 解决方案: 使用springSession框架
                 **/
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                return "redirect:http://gulimall.com";
            } else {
                return "http:/login.html";
            }
        } else {
            return "http:/login.html";
        }
    }
}
